package com.teacher.hong.dao;

import com.teacher.hong.entity.Clazz;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 处理班级表数据的类
 */
@Repository
public class ClazzDao {

    public ClazzDao() {
        System.out.println("创建ClazzDao");
    }

    @Resource
    private BaseDao baseDao;

//    public void setBaseDao(BaseDao baseDao) {
//        this.baseDao = baseDao;
//        System.out.println("执行ClazzDao的setBaseDao函数...");
//    }

    /**
     * 查询所有班级数据
     *
     * @return
     */
    public List<Clazz> select() throws SQLException {
        List<Clazz> clazzes = new ArrayList<>();
        ResultSet resultSet = baseDao.query("select * from clazz;");
        while (resultSet.next()) {
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            clazzes.add(new Clazz(id, name));
        }
        return clazzes;
    }

    /**
     * 根据班级名称查询条数
     * @param name
     * @return
     */
    public int selectCountByName(String name) throws SQLException {
        int rowCount = -1;
        ResultSet resultSet = baseDao.query("select count(0) from clazz where name=?",
                Arrays.asList(name));
        if (resultSet.next()) {
            rowCount = resultSet.getInt(1);
        }
        resultSet.close();
        return rowCount;
    }


    /**
     * 根据班级ID查询条数
     * @param id
     * @return
     */
    public int selectCountById(int id) throws SQLException {
        int rowCount = -1;
        ResultSet resultSet = baseDao.query("select count(0) from clazz where id=?",
                Arrays.asList(id));
        if (resultSet.next()) {
            rowCount = resultSet.getInt(1);
        }
        return rowCount;
    }

    /**
     * 将一个clazz对象插入到数据库
     *
     * @param clazz
     * @return 影响行数
     */
    public int insert(Clazz clazz) throws SQLException {
        return baseDao.update("insert into clazz values(default, ?)",
                Arrays.asList(clazz.getName()));
    }

    /**
     * 修改class对象到数据库
     * @param clazz
     * @return
     */
    public int update(Clazz clazz) throws SQLException {
        return baseDao.update("update clazz set name=? where id=?",
                Arrays.asList(clazz.getName(), clazz.getId()));
    }

    /**
     * 根据ID删除班级数据
     * @param id
     * @return
     */
    public int delete(int id) throws SQLException {
        return baseDao.update("delete from clazz where id=?",
                Arrays.asList(id));
    }
}
